package com.wang.common.utils;

import com.wang.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;

@Slf4j
public class ClassUtil {

    /**
     * 获取包下所有类
     */
    public static List<String> getClassNameByPackage(String path) {
        List<String> className = new ArrayList<>();
        File file = new File(path);
        File[] files = file.listFiles();
        for (File f : Objects.requireNonNull(files)) {
            if (f.isDirectory()) {
                className.addAll(getClassNameByPackage(f.getPath()));
            } else {
                String cp = f.getPath();
                if (cp.endsWith(".class")) {
                    cp = cp.substring(cp.indexOf("\\com") + 1, cp.lastIndexOf("."));
                    cp = cp.replace("\\", ".");
                    className.add(cp);
                }
            }
        }
        return className;
    }

    /**
     * 通过属性名获取对象中该属性的值
     */
    public static Object getFieldValueByName(Object o, String fieldName) {
        if ("serialVersionUID".equals(fieldName)) return null;
        try {
            String firstLetter = fieldName.substring(0, 1).toUpperCase();
            String getter = "get" + firstLetter + fieldName.substring(1);
            Method method = o.getClass().getMethod(getter);
            return method.invoke(o);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获得实体类的 非空键值对
     */
    public static Map<String, String> getMap(Object entity) throws Exception {
        Map<String, String> map = new HashMap<>();
        try {
            Field[] fields = entity.getClass().newInstance().getClass().getDeclaredFields();
            Arrays.stream(fields).forEach(field -> {
                String name = field.getName();
                String fieldValue = (String) getFieldValueByName(entity, name);
                if (Utils.isNotEmpty(fieldValue)) {
                    map.put(name, fieldValue);
                }
            });
        } catch (InstantiationException | IllegalAccessException e) {
            throw new Exception("getMap非空键值对获取失败", e);
        }
        return map;
    }
}
